﻿using FlickrNet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace TrailImage
{
	/// <summary>
	/// http://www.switchonthecode.com/tutorials/csharp-tutorial-binding-a-datagridview-to-a-collection
	/// </summary>
	public class Link : INotifyPropertyChanged
	{
		string _id;
		string _title;
		string _blogSecret;
		string _flickrSecret;

		[Browsable(false)]
		public event PropertyChangedEventHandler PropertyChanged;

		void Changed(params string[] name)
		{
			if (this.PropertyChanged != null)
			{
				foreach (string n in name)
				{
					this.PropertyChanged(this, new PropertyChangedEventArgs(n));
				}
			}
		}

		public string Name
		{
			get { return (string.IsNullOrEmpty(_title) ? _id : _title);	}
		}

		internal string ID
		{
			get { return _id; }
			set { _id = value; this.Changed("ID"); }
		}
		internal string Title
		{
			get { return _title; }
			set { _title = value; this.Changed("Title", "Name"); }
		}

		internal string BlogSecret
		{
			get { return _blogSecret; }
			set { _blogSecret = value; this.Changed("BlogSecret"); }
		}

		internal string FlickrSecret
		{
			get { return _flickrSecret; }
			set { _flickrSecret = value; this.Changed("FlickrSecret", "IsValid"); }
		}

		/// <summary>
		/// Update values with information from Flickr
		/// </summary>
		internal void Update(PhotoInfo info)
		{
			this.FlickrSecret = info.Secret;
			this.Title = info.Title;
		}

		public bool? IsValid
		{
			get {
				if (string.IsNullOrEmpty(_flickrSecret)) { return null; }
				else { return !this.IsChanged; }
			}
		}

		internal bool IsChanged { get { return this.FlickrSecret != this.BlogSecret; } }

		/// <summary>
		/// Find and replace old URL in HTML
		/// </summary>
		internal string UpdateUrl(string html)
		{
			if (this.IsChanged)
			{
				html = html.Replace(this.ID + "_" + this.BlogSecret, this.ID + "_" + this.FlickrSecret);
			}
			return html;
		}
	}
}
